#include <klib.h>
#include <klib-macros.h>
#include <stdint.h>

#if !defined(__ISA_NATIVE__) || defined(__NATIVE_USE_KLIB__)

size_t strlen(const char *s) {
	size_t i =0;
	for(i=0;*(s+i)!='\0';i++){	
	}
	return i;
}

char *strcpy(char *dst, const char *src) {
	size_t i = 0;
	for(i=0;*(src+i)!= '\0';i++){
		*(dst+i) = *(src+i);
	}
	*(dst+i) = *(src+i);
	return dst;
}

char *strncpy(char *dst, const char *src, size_t n) {
	size_t i;
  for (i = 0; i < n && src[i] != '\0'; i++)
	{dst[i] = src[i];}
  for ( ; i < n; i++)
	{dst[i] = '\0';}

	return dst;
}

char *strcat(char *dst, const char *src) {
	size_t dest_len = strlen(dst);
	size_t i;
	for (i = 0 ;  src[i] != '\0' ; i++)
	{
		dst[dest_len + i] = src[i];
	}
	dst[dest_len + i] = '\0';
	return dst;
	}

int strcmp(const char *s1, const char *s2) {
	const char *p = s1;
	const char *q = s2;
	while(*p == *q){
		if(*p == '\0'){
			return 0;
		}
		p++;
		q++;
	}
		return *p - *q;
}

int strncmp(const char *s1, const char *s2, size_t n) {
	const char *p = s1;
	const char *q = s2;
	size_t cnt = 0;
	while(*p == *q && cnt != n){
		if(*p == '\0'){
			return 0;
		}
		p++;
		q++;
		cnt++;
	}
	if(cnt == n) return 0;
	else return *p-*q;
}

void *memset(void *s, int c, size_t n) {
	char* s1 = (char*) s;
	size_t i = 0;
	for (;i<n;i++){
		s1[i] = c;
	}
	return s;
}

void *memmove(void *dst, const void *src, size_t n) {
    void* ret = dst;
    if (dst <= src || (char*)dst >= ((char*)src + n))
    {
  
        while (n--) {
            *(char*)dst = *(char*)src;
            dst = (char*)dst + 1;
            src = (char*)src + 1;
        }
    }
    else {
        dst = (char*)dst + n - 1;
        src = (char*)src + n - 1;
        while (n--) { 
            *(char*)dst = *(char*)src;
            dst = (char*)dst - 1;
            src = (char*)src - 1;
        }
    }
    return(ret);
}

void *memcpy(void *out, const void *in, size_t n) {
	for(size_t i= 0; i<n;i++){
		*((char*)out + i) = *((char*)in + i);
	}
	return out;
}

int memcmp(const void *s1, const void *s2, size_t n) {
	const char *p = (char*)s1;
	const char *q = (char*)s2;
	size_t cnt = 0;
	while(*p == *q && cnt != n){
		if(*p == '\0'){
			return 0;
		}
		p++;
		q++;
		cnt++;
	}
	if(cnt == n) return 0;
	else return *p-*q;
}

#endif
